import React, {useRef} from 'react';
import { observer } from "mobx-react-lite";
import todoStore from '../store/todoStore';
import './index.css'

const Todo = () => {
  const inputValue = useRef(null)
  // 按下回车触发，将数据写入仓库
  const handleKeyUp = (e) => {
    if(e.key === 'Enter'){
      // console.log(inputValue.current.value);
      todoStore.setList(inputValue.current.value)
      inputValue.current.value = ''
    }
  }

  // 某一项状态改变，修改isDone
  const handleChange = (id) => {
    // console.log(id);
    todoStore.checkItem(id)
  }

  // 是否全选
  const handleAllchecked = (e) => {
    // console.log(e.target.checked);
    todoStore.allChecked(e.target.checked)
  }

  // 每一项的isDone为true则为true
  const isAllChecked = todoStore.list.every(item => item.isDone);

  // 删除
  const handleDel = (id) => {
    todoStore.deleteTodo(id)
  }
  return (
    <section className="todoapp">
      <header className="header">
        <h1>todos</h1>
        <input
          className="new-todo"
          autoFocus
          autoComplete="off"
          placeholder="What needs to be done?"
          ref={inputValue}
          onKeyUp={handleKeyUp}
        />
      </header>

      <section className="main">
        {/* 全选 */}
        <input
          id="toggle-all"
          className="toggle-all"
          type="checkbox"
          checked={isAllChecked}
          onChange={(e) => handleAllchecked(e)}
        />
        <label htmlFor="toggle-all"></label>
        
        <ul className="todo-list">
          {
            todoStore.list.map(item => (
              <li className={item.isDone ? "todo completed" : "todo"} key={item.id}>
                <div className="view">
                  <input className="toggle" type="checkbox" checked={item.isDone} onChange={() => handleChange(item.id)}/>
                  <label>{item.name}</label>
                  <button className="destroy" onClick={() => handleDel(item.id)}></button>
                </div>
              </li>
            ))
          }
        </ul>
      </section>
    </section>
  );
};

export default observer(Todo);